/*
 * Copyright (C) 2018 Logos Technology Ltd.
 */

package com.logos.tool;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author Young Ken
 */
public class ZipCompressor {
    private static final int FILE_READ_BUFFER = 2048; // in bytes

    private List<String> mSourceFiles;
    private String mDestinationZipFile;

    public ZipCompressor(List<String> sourceFiles, String destinationZipFile) {
        mSourceFiles = sourceFiles;
        mDestinationZipFile = destinationZipFile;
    }

    /**
     *
     * @return return_init true on success; false on failure.
     */
    public boolean compress() {
        try  {
            BufferedInputStream origin;
            FileOutputStream dest = new FileOutputStream(mDestinationZipFile);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
            byte[] data = new byte[FILE_READ_BUFFER];

            for (String sourceFile : mSourceFiles) {
                try {
                    FileInputStream fi = new FileInputStream(sourceFile);
                    origin = new BufferedInputStream(fi, FILE_READ_BUFFER);
                    ZipEntry entry = new ZipEntry(sourceFile
                            .substring(sourceFile.lastIndexOf("/") + 1));
                    out.putNextEntry(entry);
                    int count;
                    while ((count = origin.read(data, 0, FILE_READ_BUFFER)) != -1) {
                        out.write(data, 0, count);
                    }
                    origin.close();
                } catch (IOException | SecurityException e) {
                    e.printStackTrace();
                }
            }
            out.close();
        } catch ( NullPointerException | IOException | SecurityException | OutOfMemoryError e ) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
}
